﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.MaterialDetail;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;
using ERP_SaaS_WinForm.登录.Common;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class SelectMaterial : Form
    {
        private DataGridView dgvMaterials;
        private TextBox txtSearch;
        private Button btnSearch;
        private Button btnSelect;
        private Button btnCancel;
        private List<MaterialDetailData> materialList = new List<MaterialDetailData>();
        
        // 选中的物料
        public MaterialDetailData SelectedMaterial { get; private set; }

        public SelectMaterial()
        {
            InitializeComponent();
            
            // 检查JWT授权状态
            if (!JwtAuthHelper.EnsureLoggedIn())
            {
                MessageBox.Show("需要登录才能使用此功能", "授权提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.Close();
                return;
            }
            
            InitializeCustomComponents();
            LoadMaterialData();
        }

        private void InitializeCustomComponents()
        {
            // 设置窗体标题和大小
            this.Text = "选择物料";
            this.Size = new Size(1200, 700);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 创建搜索面板
            Panel searchPanel = new Panel();
            searchPanel.Dock = DockStyle.Top;
            searchPanel.Height = 60;
            searchPanel.BackColor = Color.LightGray;

            // 创建搜索控件
            Label lblSearch = new Label();
            lblSearch.Text = "搜索物料:";
            lblSearch.Location = new Point(20, 20);
            lblSearch.Size = new Size(80, 20);

            txtSearch = new TextBox();
            txtSearch.Location = new Point(110, 18);
            txtSearch.Size = new Size(200, 25);
            // 移除 PlaceholderText，因为 .NET Framework 不支持此属性

            btnSearch = new Button();
            btnSearch.Text = "搜索";
            btnSearch.Location = new Point(320, 18);
            btnSearch.Size = new Size(80, 25);
            btnSearch.BackColor = Color.LightBlue;
            btnSearch.Click += BtnSearch_Click;

            // 添加搜索控件到面板
            searchPanel.Controls.AddRange(new Control[] { lblSearch, txtSearch, btnSearch });

            // 创建DataGridView
            dgvMaterials = new DataGridView();
            dgvMaterials.Dock = DockStyle.Fill;
            dgvMaterials.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvMaterials.AllowUserToAddRows = false;
            dgvMaterials.ReadOnly = true;
            dgvMaterials.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvMaterials.MultiSelect = false;
            dgvMaterials.RowHeadersVisible = false;
            dgvMaterials.BackgroundColor = Color.White;
            dgvMaterials.GridColor = Color.LightGray;
            dgvMaterials.BorderStyle = BorderStyle.None;
            dgvMaterials.CellDoubleClick += DgvMaterials_CellDoubleClick;

            // 创建按钮面板
            Panel buttonPanel = new Panel();
            buttonPanel.Dock = DockStyle.Bottom;
            buttonPanel.Height = 50;
            buttonPanel.BackColor = Color.White;

            btnSelect = new Button();
            btnSelect.Text = "选择";
            btnSelect.Size = new Size(80, 30);
            btnSelect.Location = new Point(20, 10);
            btnSelect.BackColor = Color.LightGreen;
            btnSelect.Click += BtnSelect_Click;

            btnCancel = new Button();
            btnCancel.Text = "取消";
            btnCancel.Size = new Size(80, 30);
            btnCancel.Location = new Point(120, 10);
            btnCancel.BackColor = Color.LightGray;
            btnCancel.Click += BtnCancel_Click;

            // 添加按钮到面板
            buttonPanel.Controls.AddRange(new Control[] { btnSelect, btnCancel });

            // 添加控件到窗体
            this.Controls.Add(dgvMaterials);
            this.Controls.Add(buttonPanel);
            this.Controls.Add(searchPanel);
        }

        private async void LoadMaterialData()
        {
            try
            {
                // 检查JWT授权状态
                if (!JwtAuthHelper.CheckLoginStatus())
                {
                    return;
                }
                
                btnSearch.Enabled = false;
                btnSearch.Text = "加载中...";

                using (var client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 添加JWT授权头
                    if (TokenDto.IsLoggedIn)
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenDto.JwtToken);
                        Console.WriteLine("已添加JWT授权头");
                    }
                    
                    var response = await client.GetAsync("http://10.223.8.23:8008/api/Material/GetMaterialInfo");
                    
                    // 检查响应状态
                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        Console.WriteLine("物料API返回401未授权错误");
                        var result = MessageBox.Show("登录已过期，是否重新登录？", "登录过期", 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        
                        if (result == DialogResult.Yes)
                        {
                            // 清除当前token
                            TokenDto.Clear();
                            
                            // 打开登录窗体
                            var loginForm = new LoginForm();
                            loginForm.ShowDialog();
                            
                            // 如果重新登录成功，重新调用API
                            if (TokenDto.IsLoggedIn)
                            {
                                LoadMaterialData();
                                return;
                            }
                        }
                        return;
                    }
                    
                    response.EnsureSuccessStatusCode();
                    
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse>(jsonResponse);

                    if (apiResponse != null && apiResponse.code == 200 && apiResponse.data != null)
                    {
                        materialList = apiResponse.data;
                        SetupDataGridView();
                        LoadDataToGrid(materialList);
                    }
                    else
                    {
                        MessageBox.Show($"获取数据失败: {apiResponse?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnSearch.Enabled = true;
                btnSearch.Text = "搜索";
            }
        }

        private void SetupDataGridView()
        {
            dgvMaterials.Columns.Clear();

            // 添加列并设置标题
            dgvMaterials.Columns.Add("MaterialId", "物料ID");
            dgvMaterials.Columns.Add("MaterialCode", "物料编号");
            dgvMaterials.Columns.Add("MaterialName", "物料名称");
            dgvMaterials.Columns.Add("Specification", "规格型号");
            dgvMaterials.Columns.Add("Unit", "单位");
            dgvMaterials.Columns.Add("Attribute", "物料属性");
            dgvMaterials.Columns.Add("CurrentInventory", "当前库存");
            dgvMaterials.Columns.Add("PurchasePrice", "采购价格");
            dgvMaterials.Columns.Add("MaterialState", "物料状态");

            // 设置列宽
            dgvMaterials.Columns["MaterialId"].Width = 80;
            dgvMaterials.Columns["MaterialCode"].Width = 120;
            dgvMaterials.Columns["MaterialName"].Width = 150;
            dgvMaterials.Columns["Specification"].Width = 120;
            dgvMaterials.Columns["Unit"].Width = 80;
            dgvMaterials.Columns["Attribute"].Width = 100;
            dgvMaterials.Columns["CurrentInventory"].Width = 100;
            dgvMaterials.Columns["PurchasePrice"].Width = 100;
            dgvMaterials.Columns["MaterialState"].Width = 100;

            // 设置标题行样式
            dgvMaterials.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
            dgvMaterials.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black;
            dgvMaterials.ColumnHeadersDefaultCellStyle.Font = new Font(dgvMaterials.Font, FontStyle.Bold);
            dgvMaterials.ColumnHeadersHeight = 35;
            dgvMaterials.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

            // 设置交替行颜色
            dgvMaterials.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
        }

        private void LoadDataToGrid(List<MaterialDetailData> materials)
        {
            dgvMaterials.Rows.Clear();

            foreach (var material in materials)
            {
                int rowIndex = dgvMaterials.Rows.Add();
                dgvMaterials.Rows[rowIndex].Cells["MaterialId"].Value = material.MaterialId;
                dgvMaterials.Rows[rowIndex].Cells["MaterialCode"].Value = material.MaterialCode;
                dgvMaterials.Rows[rowIndex].Cells["MaterialName"].Value = material.MaterialName;
                dgvMaterials.Rows[rowIndex].Cells["Specification"].Value = material.Specification;
                dgvMaterials.Rows[rowIndex].Cells["Unit"].Value = material.Unit;
                dgvMaterials.Rows[rowIndex].Cells["Attribute"].Value = material.Attribute ? "是" : "否";
                dgvMaterials.Rows[rowIndex].Cells["CurrentInventory"].Value = material.CurrentInventory;
                dgvMaterials.Rows[rowIndex].Cells["PurchasePrice"].Value = material.PurchasePrice.ToString("F2");
                dgvMaterials.Rows[rowIndex].Cells["MaterialState"].Value = material.MaterialState ? "启用" : "禁用";
            }
        }

        private void BtnSearch_Click(object sender, EventArgs e)
        {
            string searchText = txtSearch.Text.Trim().ToLower();
            
            if (string.IsNullOrEmpty(searchText))
            {
                LoadDataToGrid(materialList);
                return;
            }

            var filteredMaterials = materialList.Where(m => 
                (m.MaterialCode?.ToLower().Contains(searchText) == true) ||
                (m.MaterialName?.ToLower().Contains(searchText) == true) ||
                (m.Specification?.ToLower().Contains(searchText) == true)
            ).ToList();

            LoadDataToGrid(filteredMaterials);
        }

        private void DgvMaterials_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                SelectCurrentMaterial();
            }
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            SelectCurrentMaterial();
        }

        private void SelectCurrentMaterial()
        {
            if (dgvMaterials.CurrentRow != null)
            {
                int materialId = Convert.ToInt32(dgvMaterials.CurrentRow.Cells["MaterialId"].Value);
                SelectedMaterial = materialList.FirstOrDefault(m => m.MaterialId == materialId);
                
                if (SelectedMaterial != null)
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show("请先选择一个物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
